import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import '../../style/editpersonalsonglist.css';
import { useGlobalContext } from '../GlobalContext';

const EditPersonalsonglist = () => {
  const { persongListrefresh, setPerSonglistRefresh } = useGlobalContext();
  const { playlistId } = useParams();
  const navigate = useNavigate();

  const [songData, setSongData] = useState({
    songListName: '',
    coverUrl: '',
    description: ''
  });
  const [coverFile, setCoverFile] = useState(null);  // 用于存储封面图片文件

  // 获取歌单现有信息
  useEffect(() => {
    if (playlistId) {
      fetch(`http://localhost:8088/songlist/${playlistId}`, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      })
        .then((response) => response.json())
        .then((data) => {
          setSongData(data.data); // 更新状态，将歌单数据存入 songData
        })
        .catch((error) => {
          console.error('Error fetching song data:', error);
        });
    }
  }, [playlistId]);

  // 处理封面图片选择
  const handleCoverChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      setCoverFile(file); // 存储封面图片文件
      const reader = new FileReader();
      reader.onloadend = () => {
        setSongData(prevData => ({
          ...prevData,
          coverUrl: reader.result // 设置封面图片预览
        }));
      };
      reader.readAsDataURL(file);
    }
  };

  const handleSongListNameChange = (e) => {
    setSongData(prevData => ({
      ...prevData,
      songListName: e.target.value
    }));
  };

  const handleDescriptionChange = (e) => {
    setSongData(prevData => ({
      ...prevData,
      description: e.target.value
    }));
  };

  const handleSubmit = async () => {
    try {
      const formData = new FormData();
      formData.append("songListName", songData.songListName);
      formData.append("description", songData.description);

      // 如果有封面文件，添加封面文件
      if (coverFile) {
        formData.append("file", coverFile);
      }

      const response = await fetch(`http://localhost:8088/songlist/${playlistId}`, {
        method: "PUT",
        body: formData, // 使用 FormData 发送数据
      });

      if (!response.ok) {
        throw new Error('Failed to update song list');
      }

      const updatedData = await response.json();
      setSongData(updatedData.data); // 更新状态
      setPerSonglistRefresh(!persongListrefresh);
      navigate(-1);  // 返回上一页
      alert('歌单信息已保存!');
    } catch (error) {
      console.error('Error updating song data:', error);
    }
  };

  const handleCancel = () => {
    navigate(-1); // 返回上一页，取消编辑
  };

  return (
    <div className='edit'>
      <p className="edittitle">编辑歌单信息</p>
      <div className="editmain">
        <div className="editleft">
          <div className="editcoverImg">
            {songData.coverUrl ? (
              <img src={songData.coverUrl} alt="Cover" className="cover-preview" />
            ) : (
              <img src="/img/songlistdefault.png" alt="Default Cover" />
            )}
          </div>
          <input
            type="file"
            accept="image/*"
            id="coverInput"
            style={{ display: 'none' }} // 隐藏默认的输入框
            onChange={handleCoverChange}
          />
          <div
            className="editcoverbelow"
            onClick={() => document.getElementById('coverInput').click()}
          >
            编辑封面
          </div>
        </div>

        <div className="editright">
          <p>歌单名</p>
          <input
            type="text"
            placeholder="请输入歌单名称"
            maxLength={15}
            className='inputsonglistName'
            value={songData.songListName}
            onChange={handleSongListNameChange}
          />
          <p>简介</p>
          <textarea
            placeholder="每张歌单都有自己的故事，聊一下吧"
            className="inputdescription"
            maxLength={1000}
            value={songData.description}
            onChange={handleDescriptionChange}
            rows="4"
            cols="50"
          />
          <div className="controll">
            <button onClick={handleSubmit}>保存</button>
            <button onClick={handleCancel}>取消</button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default EditPersonalsonglist;
